﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Game.Foundation;
using Game.Foundation.ChineseChess;
using Bruce.Net;
using Server.Game.Generic;

namespace Game.Server.ChineseChess
{
    class ChineseChessGameGroup : AbsGameGroup
    {
        private Chessboard _chessboard;

        public ChineseChessGameGroup(GameRoomServer room, int id)
            : base(room, id)
        { }

        protected override int PlayerCountPerGroup
        {
            get { return 2; }
        }

        protected override void InitializeNewGame()
        {
            this._chessboard = new Chessboard();
            this._chessboard.Completed += new EventHandler(_chessboard_Completed);
        }

        void _chessboard_Completed(object sender, EventArgs e)
        {
            this._completed = true;

            Packet p = new Packet((int)PacketType.游戏结束通知);
            p.WriteInt32(this._playerArray.Length);

            p.WriteString(this._playerArray[this._step % PlayerCountPerGroup].UserName);
            p.WriteInt32(5);

            p.WriteString(this._playerArray[(this._step + 1) % PlayerCountPerGroup].UserName);
            p.WriteInt32(-5);


            foreach (var item in this._playerArray.Where(pp => pp != null))
            {
                item.SendMessage(p);
                item.Status = GameStatus.Unready;
            }

            this.OnGameCompleted();
        }

        public override void SynchronizeGame(Packet p)
        {
            Player proxy = p.GetRelationData<Player>();
            if (proxy == null)
            {
                return;
            }

            int xold = p.ReadInt32();
            int yold = p.ReadInt32();
            int xnew = p.ReadInt32();
            int ynew = p.ReadInt32();

            bool success = Array.IndexOf<Player>(this._playerArray, proxy) == this._step % PlayerCountPerGroup;
            if (success)
            {
                success &= this._chessboard.MoveChessman(this._chessboard.GetChessman(xold, yold), xnew, ynew);
            }
            byte returnCode = (byte)(success ? 0 : 1);
            p = new Packet((int)PacketType.游戏操作返回包);
            p.OptionOne = returnCode;
            proxy.SendMessage(p);

            if (!success) return;

            p = new Packet((int)PacketType.游戏操作同步包);
            p.WriteInt32(xold);
            p.WriteInt32(yold);
            p.WriteInt32(xnew);
            p.WriteInt32(ynew);
            foreach (var item in this._playerArray)
            {
                item.SendMessage(p);
            }

            if (!this._completed)
            {
                this.ExchangeProxy();
            }
        }
    }
}
